public class O12 {
    public static void main(String[] args) {
        O12 o = new O12();
        System.out.println(o.exist(new char[][]{{'a','b'}},"ab"));
    }
    public boolean exist(char[][] board, String word) {
        char[] chs = word.toCharArray();
        try {
            for (int i = 0; i < board.length; i++)
                for (int j = 0; j < board[i].length; j++)
                    if (board[i][j]==chs[0])
                            dfs(new boolean[board.length][board[0].length],i,j,board,chs,0);
        } catch (Exception e) {
            return true;
        }
        return false;
    }
    void dfs(boolean[][] visit,int m,int n,char[][] board,char[] chs,int now){
        if (now==chs.length-1)
            m = Integer.MAX_VALUE+1;
        if (m>0&&!visit[m-1][n]&&board[m-1][n]==chs[now+1]){
            visit[m][n] = true;
            dfs(visit,m-1,n,board,chs,now+1);
            visit[m][n] = false;
        }
        if (m<board.length-1&&!visit[m+1][n]&&board[m+1][n]==chs[now+1]){
            visit[m][n] = true;
            dfs(visit,m+1,n,board,chs,now+1);
            visit[m][n] = false;
        }
        if (n>0&&!visit[m][n-1]&&board[m][n-1]==chs[now+1]){
            visit[m][n] = true;
            dfs(visit,m,n-1,board,chs,now+1);
            visit[m][n] = false;
        }
        if (n<board[0].length-1&&!visit[m][n+1]&&board[m][n+1]==chs[now+1]){
            visit[m][n] = true;
            dfs(visit,m,n+1,board,chs,now+1);
            visit[m][n] = false;
        }
    }
}
